<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="活动id" prop="actId">
        <el-input
          v-model="queryParams.actId"
          placeholder="请输入活动id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="活动标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入活动标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="活动类型" prop="actType">
        <el-select v-model="queryParams.actType" placeholder="请选择活动类型" clearable>
          <el-option
            v-for="dict in activities_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="组织者" prop="organizers">
        <el-input
          v-model="queryParams.organizers"
          placeholder="请输入组织者"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="活动状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择活动状态" clearable>
          <el-option
            v-for="dict in activities_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px;">
        <el-date-picker
            v-model="dateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['match:activities:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['match:activities:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['match:activities:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['match:activities:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="activitiesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="活动id" align="center" prop="actId" />
      <el-table-column label="活动标题" align="center" prop="title" />
      <el-table-column label="活动类型" align="center" prop="actType">
        <template #default="scope">
          <dict-tag :options="activities_type" :value="scope.row.actType"/>
        </template>
      </el-table-column>
      <el-table-column label="活动大纲" align="center" prop="actOutline" />
      <el-table-column label="组织者" align="center" prop="organizers" />
      <el-table-column label="添加时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Search" @click="getActInfoVo(scope.row)" v-hasPermi="['match:activities:query']">查看详情</el-button>
          <el-button link type="primary" icon="Search" @click="getTeamsInfo(scope.row)" v-hasPermi="['match:teams:query']">查看队伍</el-button>
          <el-button link type="primary" icon="Plus" @click="createTeamsInfo(scope.row)" v-hasPermi="['match:teams:add']">创建队伍</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['match:activities:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['match:activities:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改活动管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="activitiesRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入活动标题" />
        </el-form-item>
        <el-form-item label="活动类型" prop="actType">
          <el-select v-model="form.actType" placeholder="请选择活动类型">
            <el-option
              v-for="dict in activities_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动大纲" prop="actOutline">
          <el-input v-model="form.actOutline" placeholder="请输入活动大纲" />
        </el-form-item>
        <el-form-item label="活动详情" prop="body">
          <el-input v-model="form.body" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="组织者" prop="organizers">
          <el-input v-model="form.organizers" placeholder="请输入组织者" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

<!--    查看活动详情弹窗-->
    <el-dialog :title="活动详情" v-model="ActInfoOpen" width="1000px" append-to-body class="custom-dialog">
      <el-row>
        <el-col :span="12">活动ID：{{form.actId}}</el-col>
        <el-col :span="12">活动名称：{{form.title}}</el-col>
      </el-row>
      <el-row>
        <el-col :span="12">活动类别：{{form.actType}}</el-col>
        <el-col :span="24">活动简介：{{form.actOutline}}</el-col>
      </el-row>
      <el-row>
        <el-col :span="12">主办方：{{form.organizers}}</el-col>
        <el-col :span="24">活动创建者：{{form.createBy}}</el-col>
      </el-row>
      <el-row>
        <el-col :span="12">正文：{{form.body}}</el-col>
      </el-row>

    </el-dialog>

<!--    //根据活动id查看 队伍列表-->
    <el-dialog :title="'队伍列表'" v-model="TeamInfoOpen" width="600px" append-to-body class="custom-dialog">
      <el-table :data="teamsList" style="width: 100%">
        <el-table-column prop="teamId" label="队伍ID" width="80"></el-table-column>
        <el-table-column prop="teamName" label="队伍名称" width="150"></el-table-column>
        <el-table-column prop="leaderName" label="队长名称" width="100"></el-table-column>
        <el-table-column prop="teamOutline" label="队伍简介"></el-table-column>

        <!-- 新增操作列 -->
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="joinTeam(row.teamId)">
              加入队伍
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 添加队伍对话框 -->
    <el-dialog :title="title" v-model="addTeam" width="500px" append-to-body>
      <el-form ref="teamsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="队伍名称" prop="teamName">
          <el-input v-model="form.teamName" placeholder="请输入队伍名称" />
        </el-form-item>
        <el-form-item label="队伍简介" prop="teamOutline">
          <el-input v-model="form.teamOutline" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="活动ID" prop="actId">
          <el-input v-model="form.actId" placeholder="请输入所属活动ID" />
        </el-form-item>
        <el-form-item label="队伍状态" prop="teamStatus">
          <el-radio-group v-model="form.teamStatus">
            <el-radio
                v-for="dict in team_status"
                :key="dict.value"
                :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormTeam">确 定</el-button>
          <el-button @click="cancelTeam">取 消</el-button>
        </div>
      </template>
    </el-dialog>



  </div>
</template>






<style scoped>
.custom-dialog {
  border-radius: 12px;
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
  background-color: #fff;
  width: 600px; /* 增大对话框宽度 */
}

.custom-dialog .el-dialog__header {
  background-color: #f0f9eb;
  border-bottom: 1px solid #ebedf0;
  padding: 20px; /* 增加头部的内边距 */
}

.custom-dialog .el-dialog__title {
  color: #67c23a;
  font-size: 22px; /* 增大标题字体大小 */
  font-weight: bold; /* 标题加粗 */
}

.custom-dialog .el-row {
  margin-bottom: 20px; /* 增大行之间的间距 */
}

.custom-dialog .el-col {
  color: #333;
  font-size: 16px; /* 增大内容字体大小 */
}

.custom-dialog .el-col b {
  color: #606266;
  font-size: 18px; /* 增大加粗文本的字体 */
}

.custom-dialog .el-col .el-row {
  margin-bottom: 10px;
}

</style>

<script setup name="Activities">
import { listActivities, getActivities, delActivities, addActivities, updateActivities } from "@/api/match/activities";
import { getTeamsInfoByActId, createTeam} from "@/api/match/teams";
import { addMemberTeam } from "@/api/match/MemberTeam";
import { ElMessage } from "element-plus";
import {parseTime} from "../../../utils/ruoyi.js";


const { proxy } = getCurrentInstance();
const { activities_status, activities_type } = proxy.useDict('activities_status', 'activities_type');
const dateRange = ref([]);
const activitiesList = ref([]);
const open = ref(false);

const { team_status } = proxy.useDict('team_status');

const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
// 队伍详情
const teamsList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    actId: null,
    title: null,
    actType: null,
    organizers: null,
    status: null
  },
  rules: {
    title: [
      { required: true, message: "活动标题不能为空", trigger: "blur" }
    ],
    actType: [
      { required: true, message: "活动类型不能为空", trigger: "change" }
    ],
    actOutline: [
      { required: true, message: "活动大纲不能为空", trigger: "blur" }
    ],
    body: [
      { required: true, message: "活动详情不能为空", trigger: "blur" }
    ],
    organizers: [
      { required: true, message: "组织者不能为空", trigger: "blur" }
    ],
  }
});


const teamData = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    teamId: null,
    teamName: null,
    actId: null,
  },
  rules: {
    teamName: [
      { required: true, message: "队伍名称不能为空", trigger: "blur" }
    ],
    teamOutline: [
      { required: true, message: "队伍简介不能为空", trigger: "blur" }
    ],
    actId: [
      { required: true, message: "所属活动ID不能为空", trigger: "blur" }
    ],
  }
});


const { queryParams, form, rules } = toRefs(data);
//
// /** 查询活动管理列表 */
// function getList() {
//   loading.value = true;
//   listActivities(queryParams.value).then(response => {
//     activitiesList.value = response.rows;
//     total.value = response.total;
//     loading.value = false;
//   });
// }

/** 查询活动管理列表 */
function getList() {
  loading.value = true;
  listActivities(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    activitiesList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 取消创建队伍按钮
function cancelTeam() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    actId: null,
    title: null,
    actType: null,
    actOutline: null,
    body: null,
    organizers: null,
    createBy: null,
    createTime: null,
    status: null
  };
  proxy.resetForm("activitiesRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.actId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 创建队伍按钮操作 */
const addTeam = ref(false);
function createTeamsInfo(row){
  reset();
  addTeam.value = true;
  title.value = "创建队伍";

}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加活动管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _actId = row.actId || ids.value
  getActivities(_actId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改活动管理";
  });
}


/** 查看详情按钮操作 */
const ActInfoOpen = ref(false)
function getActInfoVo(row) {
  reset();
  const _actId = row.actId
  getActivities(_actId).then(response => {
    form.value = response.data;
    ActInfoOpen.value = true;
  });
}


/** 查看活动详情下，查询队伍列表 */
const TeamInfoOpen = ref(false)

function getTeamsInfo(row) {
  reset();
  const _actId = row.actId
  getTeamsInfoByActId(_actId).then(response => {
    // form.value = response.data;
    teamsList.value = response.rows;
    TeamInfoOpen.value = true;
  });
}


// 活动详情下查询队伍列表，实现加入队伍操作
function joinTeam(teamId) {
  if (!teamId) {
    ElMessage.error("队伍 ID 无效！");
    return;
  }

  // 构造请求数据（只传 teamId）
  const requestData = {
    teamId: teamId,
  };

  // 发送加入队伍请求
  addMemberTeam(requestData)
      .then(response => {
        if (response.code === 200) {
          ElMessage.success("成功加入队伍！");
        } else {
          ElMessage.error(response.msg || "加入队伍失败");
        }
      })
      .catch(error => {
        console.error("加入队伍失败:", error);
        ElMessage.error("加入队伍时发生错误，请稍后再试！");
      });
}




/** 提交按钮 */
function submitForm() {
  proxy.$refs["activitiesRef"].validate(valid => {
    if (valid) {
      if (form.value.actId != null) {
        updateActivities(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addActivities(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 创建队伍按钮 */
function submitFormTeam() {
  proxy.$refs["teamsRef"].validate(valid => {
    if (valid) {
      createTeam(form.value).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _actIds = row.actId || ids.value;
  proxy.$modal.confirm('是否确认删除活动管理编号为"' + _actIds + '"的数据项？').then(function() {
    return delActivities(_actIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('match/activities/export', {
    ...queryParams.value
  }, `activities_${new Date().getTime()}.xlsx`)
}

getList();
</script>
